/**
 * 以CardRExport导出的数据格式, 导入卡片数据
 */
(function () {
  const CHAR_CODE_A = 'A'.charCodeAt(0);

  function get_col_name(index) {
    const chars = [];
    while (true) {
      if (chars.length > 0) index--;
      chars.unshift(String.fromCharCode(index % 26 + CHAR_CODE_A));
      index = Math.floor(index / 26);
      if (index === 0) break;
    };
    return chars.join('');
  }

  return function ({ UID, Card, Model, data }, headers) {
    // 验证用户
    if (!UID) throw Error("无效会话");
    if (!Model || Model.length === 0) throw Error("必须为CardW明确指定Model内容");
    if (!data || data.length === 0) throw Error("无导入数据");

    const v_card = A.card[Card];

    const sheet1 = data[0];
    const rows_count = sheet1['$Rows'];
    const cols_count = sheet1['$Cols'];

    // 根据标题行, 确定每个模型字段的列位置
    const title = {};
    const ref_search = {};
    for (let c = 0; c < cols_count; c++) {
      const col_name = get_col_name(c);
      const column_title = sheet1[col_name + 1];
      if (column_title === 'ID' || Model.includes(column_title)) {
        title[col_name] = column_title;

        // 引用的字段作为查找条件，需要按引用名称分组
        if (column_title.includes('.')) {
          const [refer] = column_title.split('.');
          if (ref_search[refer]) {
            ref_search[refer].push(col_name);
          } else {
            ref_search[refer] = [col_name];
          }
        }
      }
    }

    // 组织CardW数据
    const Records = [];
    for (let r = 2; r <= rows_count; r++) {
      const record = {};
      for (let c = 0; c < cols_count; c++) {
        const col_name = get_col_name(c);
        if (title[col_name] != null) {
          record[title[col_name]] = sheet1[col_name + r];

          // 如果引用的ID值不存在，则根据条件字段动态查找
          if (!record[title[col_name]] && ref_search[title[col_name]]) {
            const ref_card = v_card.引用[title[col_name]].目标名称;
            const filters = [];
            ref_search[title[col_name]].map(col_name => {
              if (sheet1[col_name + r] == null || sheet1[col_name + r] === '') return;
              const [, ...names] = title[col_name].split('.');
              filters.push([names.join('.'), '=', sheet1[col_name + r]]);
            });
            if (filters.length) {
              const { Rows } = A.job.CardR(UID, ref_card, null, filters);
              if (Rows.length > 1) throw Error(`第${r}行的${title[col_name]}匹配到了多条记录`);
              if (Rows.length === 0) throw Error(`第${r}行的${title[col_name]}没有匹配的记录`);
              record[title[col_name]] = Rows[0].ID;
            }
          }
        }
      }
      Records.push(record);
    }

    return A.db.trans(v_card.连接名称, conn => {
      return A.job.CardW(UID, Card, Model, Records);
    });
  };
})();